import { _decorator, Component, Node, TextAsset } from 'cc';

const { ccclass, property } = _decorator;

@ccclass('ProtoMgr')
export class ProtoMgr extends Component {
    public static Instance: ProtoMgr = null;
    private pb: any = null;

    @property(TextAsset)
    private pbTexAsset: TextAsset = null;

    protected onLoad(): void {
        if (ProtoMgr.Instance === null) {
            ProtoMgr.Instance = this;
        }
        else{
            this.destroy();
            return;
        }

        this.pb = protobuf.parse(this.pbTexAsset);
        // console.log(this.pb);
    }

    public SerializeMsg(msgName, msgBody): Uint8Array {
        // console.log(msgBody);
        let rs = this.pb.root.lookupType(msgName);
        let msg =rs.create(msgBody);
        // console.log(msg);

        let buf =rs.encode(msg).finish();
        console.log(buf);
        // msg = rs.decode(buf);
        // console.log(msg);
        return buf;
    }

    public DeserializeMsg(msgName, msgBuf: Uint8Array): any {
        let rs = this.pb.root.lookupType(msgName);
        let msg =rs.decode(msgBuf);
        return msg;
    }
}


